package com.jyniubi.gmail.ums.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyniubi.gmail.common.bean.PageParamVo;
import com.jyniubi.gmail.common.bean.PageResultVo;
import com.jyniubi.gmail.ums.entity.UserEntity;
import com.jyniubi.gmail.ums.mapper.UserMapper;
import com.jyniubi.gmail.ums.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<UserEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<UserEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public Boolean checkData(String data, Integer type) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        switch (type){
            case 1: queryWrapper.eq("username",data); break;
            case 2: queryWrapper.eq("phone",data); break;
            case 3: queryWrapper.eq("email",data); break;
            default:
                return null;
        }
        return this.count(queryWrapper) == 0;
    }

    @Override
    public void register(UserEntity userEntity, String code) {
        //TODO:生成验证码

        // 2.生成盐
        String salf = StringUtils.substring(UUID.randomUUID().toString(), 0, 6);
        userEntity.setSalt(salf);
        // 3.加盐加密
        userEntity.setPassword(DigestUtils.md5Hex(userEntity.getPassword() + salf));
        // 4. 新增用户
        userEntity.setLevelId(1L);
        userEntity.setUsername(userEntity.getUsername());
        userEntity.setSourceType(1);
        userEntity.setIntegration(1000);
        userEntity.setGrowth(1000);
        userEntity.setStatus(1);
        userEntity.setCreateTime(new Date());
        this.save(userEntity);
        // 5. 删除验证码
    }

    @Override
    public UserEntity queryUser(String loginName, String password) {
        UserEntity userEntity = this.getOne(new QueryWrapper<UserEntity>().eq("username", loginName)
                .or().eq("phone", loginName)
                .or().eq("email", loginName));
        if (userEntity == null){
            return null;
        }
        password = DigestUtils.md5Hex(password + userEntity.getSalt());
        if (!StringUtils.equals(password,userEntity.getPassword())) {
            return null;
        }
        return userEntity;
    }

}